/**
 * user controller
 */

const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const User = mongoose.model('User')
const Log = mongoose.model('Log')
const Redis = require('../db/redis')
const { redisKey } = require('../config')
const productToken = require('../utils/produceToken')
const captcha = require('svg-captcha')


const register = async(ctx, next) => {
	const body = ctx.request.body
	if (!body.username || !body.password || !body.email) {
		return ctx.body = {
			success: false,
			message: '必填字段不能为空'
		}
	}

	let user = await User.findOne({
		$or: [{
			email: body.email
		}, {
			username: body.username
		}]
	})
	if (user) {
		return ctx.body = {
			success: false,
			message: '账号或者邮箱已经注册过'
		}
	}
	user = new User(body)
	let result = await user.save();
	return ctx.body = {
		success: true,
		message: '注册成功'
	}
}

const login = async(ctx, next) => {
	const body = ctx.request.body
	if (ctx.session.captcha !== body.captcha) {
		return ctx.body = {
			success: false,
			message: '验证码不正确'
		}
	}
	let user = await User.checkPassword(body.username, body.password)
	if (!user) {
		return ctx.body = {
			success: false,
			message: '没有此用户或者密码'
		}
	}

	let token = jwt.sign({
		username: user.username
	}, productToken.getCode(), {
		expiresIn: 60 * 10
	})

	ctx.session.username = user.username
	ctx.session.userid = user._id

	return ctx.body = {
		success: true,
		message: '登录成功',
		data: {
			token
		}
	}
}

const logout = async(ctx, next) => {
	ctx.cookies.set(redisKey, null)
	ctx.redirect('/login')
}

const getCaptcha = async(ctx, next) => {
	const {
		text,
		data
	} = await captcha.create();
	ctx.session.captcha = text.toLowerCase()
	ctx.status = 200
	ctx.type = 'svg'
	ctx.body = data
}

module.exports = {
	register,
	logout,
	login,
	getCaptcha
}